package net.flytiger.yjh.server.service.impl;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.opencloud.common.mybatis.base.service.impl.BaseServiceImpl;
import com.opencloud.common.utils.DateUtils;
import com.opencloud.common.utils.StringUtils;

import cn.hutool.core.util.StrUtil;
import net.flytger.yjh.client.model.dto.DemoUserAddDto;
import net.flytger.yjh.client.model.dto.DemoUserDto;
import net.flytger.yjh.client.model.entity.DemoUser;
import net.flytiger.yjh.server.mapper.BaseUserMapper;
import net.flytiger.yjh.server.service.BaseUserService;

/**
 * @author: mok
 * @date: 2018/10/24 16:33
 * @description:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BaseUserServiceImpl extends BaseServiceImpl<BaseUserMapper, DemoUser> implements BaseUserService {

    @Autowired
    private BaseUserMapper baseUserMapper;

    /**
     * 添加系统用户
     */
    @Override
    public DemoUser addUser(DemoUserAddDto baseUserAddDto) {
        // 填充默认值
        DemoUser baseUser = new DemoUser();
        BeanUtils.copyProperties(baseUserAddDto, baseUser, "birthday");
        baseUser.setBirthday(StringUtils.isNotBlank(baseUserAddDto.getBirthday()) ? DateUtils.parseDate(baseUserAddDto.getBirthday()) : null);
        baseUser.fillCreateOrUpdateInfo();
        baseUser.setNickName(StringUtils.isBlank(baseUser.getNickName()) ? baseUser.getUserName() : baseUser.getNickName());
        // 保存用户信息
        save(baseUser);
        return baseUser;
    }

    /**
     * 查询列表
     */
    @Override
    public List<DemoUser> getUserList(DemoUserDto baseUserDto) {
        return baseUserMapper.getUserList(baseUserDto);
    }

    /**
     * 分页查询
     *
     * @param query
     * @return
     */
    @Override
    public IPage<DemoUser> findListPage(DemoUserDto query) {
        QueryWrapper<DemoUser> queryWrapper = new QueryWrapper();
        queryWrapper.lambda()
                .like(StrUtil.isNotBlank(query.getNickName()), DemoUser::getNickName, query.getNickName());
        return page(query.getPage(), queryWrapper);
    }

    /**
     * 更新系统用户
     */
    @Override
    public void updateUser(DemoUser baseUser) {
        Preconditions.checkArgument(baseUser != null && baseUser.getId() != null, "用户不能为空");
        baseUser.fillUpdateInfo();
        baseUserMapper.updateById(baseUser);
    }

    /**
     * 删除用户
     */
    @Override
    public void deleteUser(Long id) {
        DemoUser baseUser = getById(id);
        if (baseUser != null) {
            baseUserMapper.deleteById(id);
        }
    }


}
